package com.liuzhao.bio;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author liuxianzhao
 * @ClassName MySocketServer
 * @Description 阻塞型IO服务端
 * @date 2017年08月22日 06:49
 */
public class MySocketServer {
    private int protNumber = 28080;

    public MySocketServer() {

    }

    public MySocketServer(int protNumber) {
        this.protNumber = protNumber;
    }

    public void start() {
        try {
            ServerSocket serverSocket = new ServerSocket(protNumber);
            System.out.println("服务端启动...");
            Socket clientSocket = serverSocket.accept();
            BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
            PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
            String request, response;
            while ((request = in.readLine()) != null) {
                if ("Done".equals(request)) {
                    break;
                }
                response = processRequest(request);
                System.out.println("server:" + response);
                out.println(response);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            System.out.println("服务端关闭..");
        }
    }

    private String processRequest(String request) {
        System.out.println("client:" + request);
        if (request.contains("你好")) {
            return "你好";
        }
        return "今天天气不错";
    }
}
